#include "sessionmanager.h"
#include "../network/networkloginrequest.h"
#include "../network/networkmanager.h"
#include "../network/networkfailedresponse.h"
#include "../network/networkloginedresponse.h"

using namespace Session;
Manager *Manager::m_instance = NULL;
Manager::Manager(QObject *parent) :
    QObject(parent),
    m_loginRequest(NULL)
{
}

bool Manager::login(const QString &user, const QString &password)
{
    if (m_loginRequest != NULL)
        return false;
    m_loginRequest = new network::LoginRequest(user, password, this);
    connect(m_loginRequest, &network::Request::responsed, this, &Manager::onResponsed);
    network::Manager *manager = network::Manager::instance();
    if (!manager->execute(m_loginRequest)) {
        delete m_loginRequest;
        m_loginRequest = NULL;
        return false;
    }
    return true;
}


bool Manager::logout()
{
    return true;
}

Manager *Manager::instance(QObject *parent)
{
    if (m_instance == NULL)
        m_instance = new Manager(parent);
    return m_instance;
}

void Manager::onResponsed(network::Response *response)
{
    m_loginRequest->deleteLater();
    m_loginRequest = NULL;
    if (response->type() == network::Response::Failed) {
        const network::FailedResponse &failedResponse = (const network::FailedResponse &) response;
        if (failedResponse.dataError() == network::FailedResponse::NoError)
            emit logined(false, failedResponse.networkMessage(), QVariant());
        else
            emit logined(false, failedResponse.dataMessage(), QVariant());
    }

    if (response->type() != network::Response::Logined)
        return;
    network::LoginedResponse *loginedResponse = (network::LoginedResponse *)response;
    m_sessionKey = loginedResponse->sessionKey();
    emit logined(true, "Login successed", loginedResponse->data());
}

void Manager::onConnected()
{

}

void Manager::onDisconnected()
{

}
